<?php

namespace app\admin\controller\usermanage;


use app\common\controller\Backend;
use app\admin\model\usermanage\Users as UsersModel;
use app\admin\model\usermanage\UsersGroup as UsersGroupModel;

class Relation extends Backend
{
    /**
     * 查看
     */
    public function index($user_id=0)
    {
        $list = $this->buildTree($user_id);


        if ($user_id){
            $user = UsersModel::get($user_id);
            $arr = [
                'name'=>$user->account,
                //'value'=>$user->team_pv,
                'children'=>$list
            ];
        } else {
            $arr = [
                'name'=>'总平台',
                'children'=>$list
            ];
        }

        $this->assignconfig('list', $arr);

        return $this->view->fetch();
    }

    public function buildTree($rootId) {
        $children = $this->getChildren($rootId); // 假设这是获取下级列表的方法
        $tree = array();
        foreach ($children as $child) {
            $tree[] = array(
                'id' => $child['id'],
                'name' => $child['account'].$child['realname'].'('.$child['group_name'].')',
                'group_name' => $child['group_name'],
                'children' => $this->buildTree($child['id']) // 递归调用
            );
        }
        return $tree;
    }

    public function getChildren($user_id=0) {
        // 这里只是示例，应该从数据库或其他数据源获取
        $user_list = UsersModel::where(['type'=>1,'contact_id'=>$user_id])
            ->field('id,account,group_id,contact_id as pid,realname')
            ->order('id asc')->select();
        foreach ($user_list as $k=>$value){
            $group = UsersGroupModel::get($value['group_id']);
            $user_list[$k]['group_name'] = $group?$group->group_name:'';
        }
        return $user_list;
    }
}